//
//  NSString+CYString.m
//  cyjf
//
//  Created by tauCross on 2017/5/25.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "NSString+CYString.h"

#import <CommonCrypto/CommonCrypto.h>



@implementation NSString (CYString)

- (BOOL)cy_isPhoneNumber
{
    return self.length == 11 || [self hasPrefix:@"1"];
}

- (NSString *)cy_maskName
{
    if(self.length)
    {
        NSMutableString *mask = [NSMutableString string];
        for(NSInteger i = 1; i < self.length; i++)
        {
            [mask appendString:@"*"];
        }
        return [NSString stringWithFormat:@"%@%@", [self substringToIndex:1], mask];
    }
    return self;
}

- (NSString *)cy_maskIDNumber
{
    if(self.length > 7)
    {
        NSMutableString *mask = [NSMutableString string];
        for(NSInteger i = 7; i < self.length; i++)
        {
            [mask appendString:@"*"];
        }
        return [NSString stringWithFormat:@"%@%@%@", [self substringToIndex:3], mask, [self substringFromIndex:self.length - 4]];
    }
    return self;
}

- (NSString *)cy_maskPhoneNumber
{
    if(self.length == 11)
    {
        return [NSString stringWithFormat:@"%@****%@", [self substringToIndex:3], [self substringFromIndex:self.length - 4]];
    }
    return self;
}

- (NSString *)cy_maskCardNumber
{
    if(self.length > 4)
    {
        return [NSString stringWithFormat:@"**** **** **** %@", [self substringFromIndex:self.length - 4]];
    }
    return self;
}

- (NSString *)cy_suffixCardNumber
{
    if(self.length > 4)
    {
        return [self substringFromIndex:self.length - 4];
    }
    return self;
}

- (NSDate *)cy_dateWithFormat:(NSString *)format
{
    return [[NSDateFormatter cy_formatterWithFormat:format] dateFromString:self];
}

- (NSString *)cy_desDecrypt
{
    NSData *dataIn = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSMutableData *key = [[@"5Df8$&@S" dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
    key.length = kCCBlockSizeDES;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    bufferPtrSize = ([self length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
    bufferPtr = malloc(bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x00, bufferPtrSize);
    CCCrypt(kCCDecrypt,
            kCCAlgorithmDES,
            kCCOptionPKCS7Padding,
            [key bytes],
            [key length],
            [key bytes],
            [dataIn bytes],
            [dataIn length],
            (void *)bufferPtr,
            bufferPtrSize,
            &movedBytes);
    NSData *resultData = [[NSData alloc] initWithBytes:bufferPtr length:movedBytes];
    NSString *result = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    return result;
}

@end
